package com.dzu.gulimall.ware.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dzu.common.exception.NoStockException;
import com.dzu.common.mq.StockDetailTo;
import com.dzu.common.mq.StockLockedTo;
import com.dzu.common.to.OrderTo;
import com.dzu.common.utils.PageUtils;
import com.dzu.common.utils.Query;
import com.dzu.common.utils.R;
import com.dzu.gulimall.ware.constant.WareOrderTaskDetailConstant;
import com.dzu.gulimall.ware.dao.WareSkuDao;
import com.dzu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.dzu.gulimall.ware.entity.WareOrderTaskEntity;
import com.dzu.gulimall.ware.entity.WareSkuEntity;
import com.dzu.gulimall.ware.feign.OrderFeignService;
import com.dzu.gulimall.ware.feign.ProductFeignService;
import com.dzu.gulimall.ware.service.WareOrderTaskDetailService;
import com.dzu.gulimall.ware.service.WareOrderTaskService;
import com.dzu.gulimall.ware.service.WareSkuService;
import com.dzu.gulimall.ware.vo.OrderVo;
import com.dzu.gulimall.ware.vo.SkuHasStockVo;
import com.dzu.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {


    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private OrderFeignService orderFeignService;




    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        // 库存解锁
        wareSkuDao.unlockStock(skuId, wareId, num);

        // 更新库存单状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        entity.setLockStatus(WareOrderTaskDetailConstant.UNLOCK);
        wareOrderTaskDetailService.updateById(entity);
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         *    wareId: 123,//仓库id
         *    skuId: 123//商品id
         */
        QueryWrapper<WareSkuEntity> wareSkuEntityQueryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (StringUtils.isNotEmpty(skuId)) {
            wareSkuEntityQueryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotEmpty(wareId)) {
            wareSkuEntityQueryWrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wareSkuEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(entities == null || entities.size() == 0){
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

                if(info.getCode() == 0){
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){

            }


            wareSkuDao.insert(skuEntity);
        }else{
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuId) {

        List<SkuHasStockVo> collect = skuId.stream().map(id -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            Long count = baseMapper.getSkuStock(id);
            skuHasStockVo.setSkuId(id);
            skuHasStockVo.setHasStock(count != null && count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为某个订单锁定库存
     *
     * 库存解锁的场景：
     *  1、下订单成功，订单过期没有支付被系统自动取消，被用户手动取消。都要解锁库存
     *
     *  2、下订单成功，库存锁定成功，接下来的其他业务调用失败，导致订单回滚，之前锁定的库存就要自动解锁。
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public Boolean orderLockStock(WareSkuLockVo vo) {

        // 保存库存工作单的详情。追溯、

        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);
        Long orderTaskEntityId = wareOrderTaskEntity.getId();



        // 找到每个商品在哪个库存有库存
        List<SkuWareHasStock> hasStockList = vo.getLocks().stream().map(lock -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuId = lock.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            skuWareHasStock.setNum(lock.getCount());
            // 查询商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            if (CollUtil.isEmpty(wareIds)) {
                // 没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            skuWareHasStock.setWareIds(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());

        // 锁定库存

        for (SkuWareHasStock skuWareHasStock : hasStockList) {
            boolean skuStocked = false;
            Long skuId = skuWareHasStock.getSkuId();
            List<Long> wareIds = skuWareHasStock.getWareIds();
            Integer num = skuWareHasStock.getNum();

            // 如果每个商品都锁定成功，将当前商品锁定了几件的工作单发送记录给MQ
            // 如果锁定失败： 前面保存的的工作单信息就回滚了，发送出去的消息，即便要解锁记录，由于数据库回滚，查不到保存的工作单，所以也就不用解锁
            for (Long wareId : wareIds) {
                // 成功返回1，失败返回0
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, num);
                if (count == 1) {
                    skuStocked = true;
                    // TODO 告诉mq、库存锁定成功
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, "", num, orderTaskEntityId, wareId, WareOrderTaskDetailConstant.LOCKED);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);

                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(orderTaskEntityId);
                    // 不能只发id，防止锁定失败回滚找不到工作单数据
                    stockLockedTo.setDetail(BeanUtil.copyProperties(wareOrderTaskDetailEntity, StockDetailTo.class));
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
                    break;
                }
            }
            // 所有仓库都没锁定成功
            if (!skuStocked) {
                throw new NoStockException(skuId);
            }
        }

        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();

        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(detailId);

        // 当前工作单详情状态1.已锁定，才可以解锁
        if (detailEntity != null && detailEntity.getLockStatus().equals(WareOrderTaskDetailConstant.LOCKED)) {

            Long taskId = to.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(taskId);
            String orderSn = taskEntity.getOrderSn();
            OrderVo orderVo = orderFeignService.getOrderStatus(orderSn);
            // 订单不存在
            if (orderVo == null || orderVo.getStatus() == 4) {
                // 订单已经被取消了，才能解锁库存
                unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
            }
        }

    }

    /**
     * 防止订单服务卡顿，导致订单状态消息一直改不了，库存消息优先到期。，查询订单状态是新建状态，什么都不做就走了
     * 当值卡顿的订单，永远也不能解锁库存
     * @param orderTo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        OrderVo orderVo = orderFeignService.getOrderStatus(orderSn);
        // 查一下最新的库存的状态！！！防止重复解锁库存
        WareOrderTaskEntity wareOrderTask = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long taskId = wareOrderTask.getId();
        // 按照工作单找到所有，没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> taskDetailEntityList = wareOrderTaskDetailService.list(new LambdaQueryWrapper<WareOrderTaskDetailEntity>()
                .eq(WareOrderTaskDetailEntity::getTaskId, taskId)
                .eq(WareOrderTaskDetailEntity::getLockStatus, WareOrderTaskDetailConstant.LOCKED));

        for (WareOrderTaskDetailEntity entity : taskDetailEntityList) {
            unLockStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }

    }

}

@Data
class SkuWareHasStock {
    private Long skuId;
    private Integer num;
    private List<Long> wareIds;
}

